<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>就诊人管理</span>
          <el-button v-show="scene===1" class="button" type="primary" :icon="UserFilled" @click="scene=2">添加就诊人
          </el-button>
          <el-button v-show="scene===2" class="button" type="primary" :icon="UserFilled" @click="backHandler">返回
          </el-button>
        </div>
      </template>
      <div class="cardContent" v-show="scene===1">
        <userCard @changeScene="changeScene" @deletePatient="deletePatient"  v-for="(visitor,index) in visitorArr" :key="visitor.id" :visitor="visitor"
                  :currentIndex="index" :isDelButton="true"/>
      </div>
      <div class="visitor" v-show="scene===2">
        <el-divider content-position="left">就诊人信息</el-divider>
        <el-form :model="userParams" :status-icon="true" style="width: 60%;margin: 10px auto">
          <el-form-item label="用户姓名">
            <el-input v-model="userParams.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="证件类型">
            <el-select placeholder="请选择证件的类型" v-model="userParams.certificatesType">
              <el-option label="身份证" :value="10"></el-option>
              <el-option label="户口本" :value="20"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="证件号码">
            <el-input v-model="userParams.certificatesNo" placeholder="请输入证件号码"></el-input>
          </el-form-item>
          <el-form-item label="用户性别">
            <el-radio-group v-model="userParams.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="出生日期">
            <el-date-picker
                v-model="userParams.birthdate"
                type="date"
                label="Pick a date"
                placeholder="请你选择日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input v-model="userParams.phone" placeholder="请输入手机号码"></el-input>
          </el-form-item>
        </el-form>
        <el-divider content-position="left">建档信息（完善后部分医院首次就诊不排队建档）</el-divider>
        <el-form style="width: 60%;margin: 10px auto" :model="userParams">
          <el-form-item label="婚姻状况">
            <el-radio-group v-model="userParams.isMarry">
              <el-radio :label="1">已婚</el-radio>
              <el-radio :label="0">未婚</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="自费/医保">
            <el-radio-group v-model="userParams.isInsure">
              <el-radio :label="1">自费</el-radio>
              <el-radio :label="0">医保</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="所在地">
            <el-cascader :props="props" v-model="userParams.addressSelected"/>
          </el-form-item>
          <el-form-item label="详细地址">
            <el-input v-model="userParams.address" placeholder="请填写详细地址"></el-input>
          </el-form-item>
        </el-form>
        <el-divider content-position="left">联系人信息（选填）</el-divider>
        <el-form style="width: 60%;margin: 10px auto" :model="userParams">
          <el-form-item label="用户姓名">
            <el-input v-model="userParams.contactsName" placeholder="请输入姓名"></el-input>
          </el-form-item>

          <el-form-item label="证件类型">
            <el-select placeholder="请选择证件的类型" v-model="userParams.contactsCertificatesType">
              <el-option label="身份证" :value="10"></el-option>
              <el-option label="户口本" :value="20"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="证件号码">
            <el-input v-model="userParams.contactsCertificatesNo" placeholder="请输入证件号码"></el-input>
          </el-form-item>

          <el-form-item label="手机号码">
            <el-input v-model="userParams.contactsPhone" placeholder="请输入手机号码"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" size="default" @click="submit">提交</el-button>
            <el-button type="primary" size="default" @click="reset">重写</el-button>
          </el-form-item>
        </el-form>

      </div>

    </el-card>
  </div>
</template>

<script setup lang="ts">

import UserCard from "@/pages/Hospital/userCard.vue";
import useUserStore from "@/store/modules/user";
import useHospitalDetailStore from "@/store/modules/hospitalDetail";
import {onMounted, ref, reactive} from "vue";
import {UserFilled} from "@element-plus/icons-vue";
import {reqAddOrUpdateUser, reqCity, reqDeletePatient} from "@/api/user";
import type {CascaderProps} from 'element-plus'
import {ElMessage} from "element-plus";
import {reqFindAll} from "@/api/hospital";
import {useRoute, useRouter} from "vue-router";

let $router = useRouter();
let $route = useRoute();
let userStore = useUserStore();
let hospitalStore = useHospitalDetailStore();
let visitorArr = ref<any>([]);
let cardFlog = ref<number>(-1); //用于激活选择
let scene = ref<number>(1); //场景切换： 1.就诊人管理页面. 2.新增就诊人页面
let userParams = reactive<any>({
  id:null,
  name: "",
  certificatesType: "",
  certificatesNo: "",
  sex: 1,
  birthdate: "",
  phone: "",
  isMarry: 0,
  isInsure: 0,
  addressSelected: [],
  address: "",
  contactsName: "",
  contactsCertificatesType: "",
  contactsCertificatesNo: "",
  contactsPhone: "",
});


const props: CascaderProps = {
  lazy: true, //懒数据加载
  async lazyLoad(node, resolve) {
    let result = await reqCity(node.data.id || '86');
    let showData = result.data.map(item => {
      return {
        id: item.id,
        label: item.name,
        value: item.value,
        leaf: !item.hasChildren
      }
    });
    resolve(showData);
  }
}

const fetchUserVisitorInfo = async () => {
  try {
    await userStore.getFindAll()
    visitorArr.value = userStore.visitorInfo;

  } catch (e) {
    console.log(e.message);
  }
} //请求用户就诊人信息
const showSelect = (index) => {
  cardFlog.value = index;
}

const changeScene = (visitor) => {
  scene.value = 2;
  Object.assign(userParams,visitor)
}
const  deletePatient = async (id) => {
  console.log(id);
  let result = await reqDeletePatient(id);
  console.log(result);
  fetchUserVisitorInfo();
  ElMessage({type:"success",message:'删除成功'})
}


// submit按钮提交表单数据
const submit = async () => {
  //要么新增就诊人|更新一个已有的就诊人
  try {
    //要么新增用户成功|更新已有的用户成功
    await reqAddOrUpdateUser(userParams);
    //提示文字
    ElMessage({
      type: "success",
      message: userParams.id ? "更新成功" : "新增成功",
    });
    //提交按钮的时候判断是不是从预约挂号而来
    if ($route.query.type) {
      $router.back();
    } else {
      scene.value = 1;
    }
    reset();
    //在获取全部的就诊人的信息
    fetchUserVisitorInfo();
  } catch (error) {
    ElMessage({
      type: "success",
      message: userParams.id ? "更新失败" : "新增失败",
    });
  }
};
// reset按钮清空表单数据
const reset = () => {
  Object.assign(userParams, {
    id:null,
    name: "",
    certificatesType: "",
    certificatesNo: "",
    sex: 0,
    birthdate: "",
    phone: "",
    isMarry: 0,
    isInsure: 0,
    addressSelected: [],
    address: "",
    contactsName: "",
    contactsCertificatesType: "",
    contactsCertificatesNo: "",
    contactsPhone: "",
  });
};
// 处理返回按钮
const backHandler = () => {
  scene.value = 1;
  if($route.query.type)  $router.back()
}

onMounted(() => {
  fetchUserVisitorInfo();
  // 判断是否从预约步骤2跳转过来
  if ($route.query.type=='add') {
    scene.value = 2;
  }
  if ($route.query.type == "edit") {
    scene.value = 2;
    setTimeout(() => {
      let user  = visitorArr.value.find((item:any)=>{
        return item.id==$route.query.id;
      });
      Object.assign(userParams,user)
    },500)

  }
})
</script>


<style scoped lang="less">

:deep(.card-header) {
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    font-size: 16px;
  }
}

.cardContent {
  display: flex;
  flex-wrap: wrap;
}
</style>